package com.example.bgdharaniPlayer.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bgdharaniPlayer.R;
import com.example.bgdharaniPlayer.adapter.TrackTableAdapter;
import com.example.bgdharaniPlayer.model.AudioTrack;
import com.example.bgdharaniPlayer.model.Playlist;
import com.example.bgdharaniPlayer.service.MusicService;
import com.example.bgdharaniPlayer.util.PlaylistStorage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int REQUEST_PERMISSIONS_CODE = 100;
    private long lastPlayNowActionTime = 0;
    private static final long ACTION_TIMEOUT = 2000; // 2秒内的重复操作将被忽略
    private static final int PROGRESS_UPDATE_INTERVAL = 500; // 500毫秒更新一次进度
    
    // 播放进度条相关控件
    private SeekBar seekBarPlayback;
    private TextView tvCurrentTime;
    private TextView tvTotalTime;
    private TextView tvRepeatInfo;
    
    // 进度条更新定时器
    private Handler progressHandler;
    private Runnable progressRunnable;

    private Button btnPlayPause, btnPlaylistManager, btnSettings;
    private TextView tvCurrentTrack;
    private SeekBar seekBarVolume;
    private RecyclerView rvCurrentPlaylist;
    private TrackTableAdapter trackAdapter;
    private List<AudioTrack> currentTracks = new ArrayList<>();

    private MusicService musicService;
    private boolean isBound = false;// 用于跟踪服务绑定状态
    
    // 用于请求权限的启动器
    private ActivityResultLauncher<String[]> requestPermissionLauncher;

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
            musicService = binder.getService();
            isBound = true;
            
            // 检查服务中是否已有正在播放的曲目
            AudioTrack currentTrack = musicService.getCurrentTrack();
            
            // 只有当服务中没有正在播放的曲目时，才设置播放列表
            if (currentTrack == null && !currentTracks.isEmpty()) {
                Playlist currentPlaylist = new Playlist("当前播放列表");
                currentPlaylist.setTracks(currentTracks);
                musicService.setPlaylist(currentPlaylist);
                Log.d(TAG, "已将当前播放列表设置到服务中，共 " + currentTracks.size() + " 个音频");
            } else if (currentTrack != null) {
                Log.d(TAG, "服务中已有正在播放的曲目：" + currentTrack.getTitle() + "，不重置播放列表");
            }
            
            updateUI();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            musicService = null;
            isBound = false;
            updateUI();
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化权限请求启动器
        requestPermissionLauncher = registerForActivityResult(
            new ActivityResultContracts.RequestMultiplePermissions(),
            permissions -> {
                boolean allGranted = true;
                for (Boolean granted : permissions.values()) {
                    if (!granted) {
                        allGranted = false;
                        break;
                    }
                }
                
                if (allGranted) {
                    Log.d(TAG, "所有权限已授予");
                    startMusicService();
                } else {
                    Log.e(TAG, "部分权限被拒绝");
                    Toast.makeText(this, "需要存储和通知权限才能正常使用应用", Toast.LENGTH_LONG).show();
                }
            }
        );

        initViews();
        setupListeners();
        setupRecyclerView();
        checkAndRequestPermissions();
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntent(intent);
    }
    
    private void handleIntent(Intent intent) {
        if (intent != null) {
            String action = intent.getStringExtra("action");
            if ("play_now".equals(action)) {
                // 检查是否是新的播放请求（通过时间戳）
                long currentTime = System.currentTimeMillis();
                if (currentTime - lastPlayNowActionTime > ACTION_TIMEOUT) {
                    lastPlayNowActionTime = currentTime;
                    
                    // 从播放列表管理界面点击了播放列表，需要立即播放
                    // 先停止当前播放
                    if (isBound && musicService.isPlaying()) {
                        musicService.stop();
                    }
                    
                    // 加载新的播放列表
                    String currentPlaylistId = PlaylistStorage.getCurrentPlaylistId(this);
                    if (currentPlaylistId != null) {
                        Playlist playlist = PlaylistStorage.loadPlaylist(this, currentPlaylistId);
                        if (playlist != null) {
                            // 更新UI中的播放列表
                            currentTracks.clear();
                            currentTracks.addAll(playlist.getTracks());
                            trackAdapter.notifyDataSetChanged();
                            
                            // 更新标题显示当前播放列表名称
                            updatePlaylistHeader();
                            
                            // 设置播放列表到服务中
                            if (isBound) {
                                musicService.setPlaylist(playlist);
                                Log.d(TAG, "设置新播放列表到服务: ID=" + playlist.getId() + ", 名称=" + playlist.getName());
                                
                                // 立即播放新列表的第一条曲目
                                if (!currentTracks.isEmpty()) {
                                    musicService.play(0);
                                    Log.d(TAG, "切换播放列表：停止之前播放，开始播放新列表的第一条曲目");
                                }
                                
                                // 更新UI显示
                                updateUI();
                            } else {
                                // 如果服务未绑定，先启动服务
                                Log.d(TAG, "服务未绑定，启动服务后再播放");
                                startMusicService();
                            }
                        }
                    }
                } else {
                    Log.d(TAG, "忽略重复的播放请求");
                }
            } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                // 处理从文件管理器打开音频文件的意图
                handleViewIntent(intent);
            }
        }
    }
    
    /**
     * 处理从文件管理器打开音频文件的意图
     */
    private void handleViewIntent(Intent intent) {
        Uri audioUri = intent.getData();
        if (audioUri != null) {
            Log.d(TAG, "收到外部音频文件打开请求: " + audioUri);
            
            // 获取文件路径
            String path = getPathFromUri(audioUri);
            if (path != null) {
                try {
                    // 检查文件是否存在
                    File audioFile = new File(path);
                    if (!audioFile.exists() || !audioFile.canRead()) {
                        Log.e(TAG, "文件不存在或无法读取: " + path);
                        Toast.makeText(this, "无法访问音频文件", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    // 创建一个临时的音频轨道
                    String fileName = audioFile.getName();
                    AudioTrack track = new AudioTrack(path, fileName);
                    
                    // 创建一个临时播放列表
                    Playlist tempPlaylist = new Playlist("临时播放列表");
                    tempPlaylist.addTrack(track);
                    
                    // 保存为当前播放列表
                    PlaylistStorage.savePlaylist(this, tempPlaylist);
                    PlaylistStorage.saveCurrentPlaylistId(this, tempPlaylist.getId());
                    
                    // 更新UI中的播放列表
                    currentTracks.clear();
                    currentTracks.addAll(tempPlaylist.getTracks());
                    trackAdapter.notifyDataSetChanged();
                    
                    // 更新标题显示当前播放列表名称
                    updatePlaylistHeader();
                    
                    // 停止当前播放
                    if (isBound && musicService.isPlaying()) {
                        musicService.stop();
                    }
                    
                    // 设置播放列表到服务中并播放
                    if (isBound) {
                        musicService.setPlaylist(tempPlaylist);
                        musicService.play(0);
                        updateUI();
                        Log.d(TAG, "开始播放外部音频文件: " + fileName);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "处理外部音频文件时出错: " + e.getMessage());
                    Toast.makeText(this, "无法播放音频文件: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            } else {
                Log.e(TAG, "无法获取音频文件路径");
                Toast.makeText(this, "无法获取音频文件路径", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    /**
     * 从URI获取文件路径
     */
    private String getPathFromUri(Uri uri) {
        // 使用ContentResolver获取文件的实际路径
        String path = null;
        
        try {
            // 首先尝试使用MediaStore查询
            String[] projection = {MediaStore.Audio.Media.DATA};
            android.database.Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
            
            if (cursor != null && cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
                path = cursor.getString(column_index);
                cursor.close();
                
                if (path != null) {
                    Log.d(TAG, "通过MediaStore获取路径: " + path);
                    return path;
                }
            }
            
            // 如果MediaStore查询失败，尝试使用DocumentFile
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                // 获取持久权限
                final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
                getContentResolver().takePersistableUriPermission(uri, takeFlags);
                
                // 尝试使用DocumentFile获取文件名
                androidx.documentfile.provider.DocumentFile documentFile = 
                        androidx.documentfile.provider.DocumentFile.fromSingleUri(this, uri);
                
                if (documentFile != null && documentFile.exists()) {
                    String fileName = documentFile.getName();
                    if (fileName != null) {
                        // 创建一个临时文件来存储音频内容
                        java.io.File cacheDir = new java.io.File(getExternalCacheDir(), "audio_cache");
                        if (!cacheDir.exists()) {
                            cacheDir.mkdirs();
                        }
                        
                        java.io.File outputFile = new java.io.File(cacheDir, fileName);
                        
                        try {
                            // 复制文件内容
                            java.io.InputStream inputStream = getContentResolver().openInputStream(uri);
                            java.io.FileOutputStream outputStream = new java.io.FileOutputStream(outputFile);
                            
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }
                            
                            inputStream.close();
                            outputStream.close();
                            
                            path = outputFile.getAbsolutePath();
                            Log.d(TAG, "通过复制文件获取路径: " + path);
                            return path;
                        } catch (Exception e) {
                            Log.e(TAG, "复制文件失败: " + e.getMessage());
                        }
                    }
                }
            }
            
            // 最后尝试直接使用URI路径
            path = uri.getPath();
            Log.d(TAG, "使用URI路径: " + path);
            
        } catch (Exception e) {
            Log.e(TAG, "获取文件路径失败: " + e.getMessage());
        }
        
        // 如果所有方法都失败，返回URI的字符串表示
        if (path == null) {
            path = uri.toString();
            Log.d(TAG, "使用URI字符串: " + path);
        }
        
        return path;
    }
    
    private void checkAndRequestPermissions() {
        // 需要请求的权限列表
        java.util.List<String> permissionsToRequest = new java.util.ArrayList<>();
        
        // 检查存储权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 使用 READ_MEDIA_AUDIO 权限
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_MEDIA_AUDIO) 
                    != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(android.Manifest.permission.READ_MEDIA_AUDIO);
            }
        } else {
            // Android 12 及以下使用 READ_EXTERNAL_STORAGE 权限
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) 
                    != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
            }
        }
        
        // 检查通知权限（Android 13+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) 
                    != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(android.Manifest.permission.POST_NOTIFICATIONS);
            }
        }
        
        // 如果有需要请求的权限，则请求它们
        if (!permissionsToRequest.isEmpty()) {
            requestPermissionLauncher.launch(permissionsToRequest.toArray(new String[0]));
        } else {
            // 已经有所有需要的权限，直接启动服务
            startMusicService();
        }
    }

    private void initViews() {
        btnPlayPause = findViewById(R.id.btnPlayPause);
        btnPlaylistManager = findViewById(R.id.btnPlaylistManager);
        btnSettings = findViewById(R.id.btnSettings);
        tvCurrentTrack = findViewById(R.id.tvCurrentTrack);
        seekBarVolume = findViewById(R.id.seekBarVolume);
        rvCurrentPlaylist = findViewById(R.id.recyclerViewCurrentPlaylist);
        
        // 初始化播放进度条相关控件
        seekBarPlayback = findViewById(R.id.seekBarPlayback);
        tvCurrentTime = findViewById(R.id.tvCurrentTime);
        tvTotalTime = findViewById(R.id.tvTotalTime);
        tvRepeatInfo = findViewById(R.id.tvRepeatInfo);
        tvRepeatInfo.setVisibility(View.GONE); // 确保初始状态下不显示重复信息
        
        // 初始化进度条更新定时器
        initProgressHandler();
    }
    
    private void initProgressHandler() {
        progressHandler = new Handler(Looper.getMainLooper());
        progressRunnable = new Runnable() {
            @Override
            public void run() {
                updatePlaybackProgress();
                progressHandler.postDelayed(this, PROGRESS_UPDATE_INTERVAL);
            }
        };
    }
    
    private void setupRecyclerView() {
        rvCurrentPlaylist.setLayoutManager(new LinearLayoutManager(this));
        trackAdapter = new TrackTableAdapter(this, currentTracks);
        rvCurrentPlaylist.setAdapter(trackAdapter);
        
        // 设置点击监听器，点击列表项时立即播放对应的音频
        trackAdapter.setOnTrackClickListener(position -> {
            if (isBound && position >= 0 && position < currentTracks.size()) {
                // 先停止当前播放
                if (musicService.isPlaying()) {
                    musicService.stop();
                }
                
                // 确保服务中的播放列表与UI中的一致
                String currentPlaylistId = PlaylistStorage.getCurrentPlaylistId(this);
                if (currentPlaylistId != null) {
                    Playlist playlist = PlaylistStorage.loadPlaylist(this, currentPlaylistId);
                    if (playlist != null) {
                        // 更新服务中的播放列表
                        musicService.setPlaylist(playlist);
                        Log.d(TAG, "点击播放前更新服务中的播放列表: ID=" + playlist.getId() + ", 名称=" + playlist.getName());
                    }
                }
                
                // 立即播放选中的曲目
                musicService.play(position);
                Log.d(TAG, "点击播放曲目：" + currentTracks.get(position).getTitle());
                
                // 更新UI和适配器中的当前播放位置
                updateUI();
                trackAdapter.setCurrentPlayingPosition(position);
            }
        });
        
        // 设置长按监听器，长按列表项时显示修改播放速度和重复次数的对话框
        trackAdapter.setOnTrackLongClickListener(position -> {
            if (position >= 0 && position < currentTracks.size()) {
                showTrackSettingsDialog(position);
                return true;
            }
            return false;
        });
        
        // 加载当前播放列表
        loadCurrentPlaylist();
        
        // 更新标题显示当前播放列表名称
        updatePlaylistHeader();
    }
    
    private void loadCurrentPlaylist() {
        String currentPlaylistId = PlaylistStorage.getCurrentPlaylistId(this);
        
        if (currentPlaylistId != null) {
            Playlist playlist = PlaylistStorage.loadPlaylist(this, currentPlaylistId);
            if (playlist != null) {
                currentTracks.clear();
                currentTracks.addAll(playlist.getTracks());
                trackAdapter.notifyDataSetChanged();
                
                // 更新标题显示当前播放列表名称
                updatePlaylistHeader();
            }
        }
    }
    
    /**
     * 更新播放列表标题显示
     */
    private void updatePlaylistHeader() {
        // 获取当前播放列表ID
        String currentPlaylistId = PlaylistStorage.getCurrentPlaylistId(this);
        
        if (currentPlaylistId != null) {
            // 加载播放列表
            Playlist playlist = PlaylistStorage.loadPlaylist(this, currentPlaylistId);
            if (playlist != null && trackAdapter != null) {
                // 使用适配器的方法设置播放列表名称
                trackAdapter.setPlaylistName(playlist.getName());
                Log.d(TAG, "更新播放列表标题为: " + playlist.getName());
            }
        }
    }

    private void setupListeners() {
        // 设置进度条拖动监听器
        seekBarPlayback.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 用户拖动进度条时更新时间显示
                if (fromUser && isBound && musicService.getCurrentTrack() != null) {
                    updateTimeDisplay(progress, musicService.getTotalDuration());
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 开始拖动时暂停进度条更新
                progressHandler.removeCallbacks(progressRunnable);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 停止拖动时，设置播放位置并恢复进度条更新
                if (isBound && musicService.getCurrentTrack() != null) {
                    musicService.seekToPosition(seekBar.getProgress());
                    progressHandler.postDelayed(progressRunnable, PROGRESS_UPDATE_INTERVAL);
                }
            }
        });
        
        btnPlayPause.setOnClickListener(v -> {
            if (isBound) {
                if (musicService.isPlaying()) {
                    musicService.pause();
                    btnPlayPause.setText(R.string.play);
                } else {
                    if (musicService.isPaused()) {
                        musicService.resume();
                    } else {
                        musicService.play(0);
                    }
                    btnPlayPause.setText(R.string.pause);
                }
                updateUI();
            }
        });


        // 移除了 btnNext 和 btnPrevious 的点击监听器，因为布局中没有这些按钮

        btnPlaylistManager.setOnClickListener(v -> {
            Intent intent = new Intent(this, PlaylistManagerActivity.class);
            startActivity(intent);
        });

        btnSettings.setOnClickListener(v -> {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
        });

        seekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (isBound && fromUser) {
                    float volume = progress / 100f;
                    musicService.setVolume(volume);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 不需要实现
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 不需要实现
            }
        });
    }

    private void startMusicService() {
        Intent intent = new Intent(this, MusicService.class);
        startService(intent);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void updateUI() {
        if (isBound) {
            AudioTrack currentTrack = musicService.getCurrentTrack();
            if (currentTrack != null) {
                tvCurrentTrack.setText(currentTrack.getTitle());
                btnPlayPause.setText(musicService.isPlaying() ? R.string.pause : R.string.play);
                
                // 更新列表中的当前播放项
                int currentPosition = musicService.getCurrentTrackIndex();
                
                // 确保UI中的播放列表与服务中的一致
                if (currentPosition >= 0 && currentPosition < currentTracks.size()) {
                    // 检查当前播放的曲目是否与列表中的一致
                    AudioTrack serviceTrack = musicService.getCurrentTrack();
                    AudioTrack uiTrack = currentTracks.get(currentPosition);
                    
                    if (serviceTrack != null && uiTrack != null && 
                        !serviceTrack.getPath().equals(uiTrack.getPath())) {
                        // 如果不一致，尝试在列表中找到匹配的曲目
                        boolean found = false;
                        for (int i = 0; i < currentTracks.size(); i++) {
                            if (currentTracks.get(i).getPath().equals(serviceTrack.getPath())) {
                                currentPosition = i;
                                found = true;
                                Log.d(TAG, "找到匹配的曲目，更新播放位置到: " + i);
                                break;
                            }
                        }
                        
                        if (!found) {
                            Log.d(TAG, "在UI列表中未找到匹配的曲目，保持当前位置: " + currentPosition);
                        }
                    }
                }
                
                trackAdapter.setCurrentPlayingPosition(currentPosition);
                
                // 如果正在播放，开始更新进度条
                if (musicService.isPlaying()) {
                    startProgressUpdates();
                    updatePlaybackProgress(); // 立即更新一次
                } else {
                    stopProgressUpdates();
                }
            } else {
                tvCurrentTrack.setText(R.string.no_track_playing);
                btnPlayPause.setText(R.string.play);
                trackAdapter.setCurrentPlayingPosition(-1);
                stopProgressUpdates();
                
                // 重置进度条
                seekBarPlayback.setProgress(0);
                tvCurrentTime.setText("00:00");
                tvTotalTime.setText("00:00");
                tvRepeatInfo.setVisibility(View.GONE);
            }
            
            seekBarVolume.setProgress((int) (musicService.getVolume() * 100));
        } else {
            tvCurrentTrack.setText(R.string.no_track_playing);
            btnPlayPause.setText(R.string.play);
            trackAdapter.setCurrentPlayingPosition(-1);
            stopProgressUpdates();
            
            // 重置进度条
            seekBarPlayback.setProgress(0);
            tvCurrentTime.setText("00:00");
            tvTotalTime.setText("00:00");
            tvRepeatInfo.setVisibility(View.GONE);
        }
    }

    /**
     * 更新播放进度
     */
    private void updatePlaybackProgress() {
        if (isBound && musicService.isPlaying()) {
            AudioTrack currentTrack = musicService.getCurrentTrack();
            if (currentTrack != null) {
                // 获取当前播放进度和总时长
                int totalProgress = musicService.getTotalPlaybackProgress();
                int totalDuration = musicService.getTotalDuration();
                
                // 设置进度条最大值和当前进度
                seekBarPlayback.setMax(totalDuration);
                seekBarPlayback.setProgress(totalProgress);
                
                // 更新时间显示
                updateTimeDisplay(totalProgress, totalDuration);
                
                // 更新重复信息 - 只在重复次数大于1时显示
                int currentRepeatCount = musicService.getCurrentRepeatCount() + 1;
                int totalRepeatCount = currentTrack.getRepeatCount();
                if (totalRepeatCount > 1) {
                    tvRepeatInfo.setVisibility(View.VISIBLE);
                    String repeatInfo = "重复: " + currentRepeatCount + "/" + totalRepeatCount;
                    tvRepeatInfo.setText(repeatInfo);
                } else {
                    tvRepeatInfo.setVisibility(View.GONE);
                }
            }
        } else {
            // 如果没有播放，显示默认值
            tvCurrentTime.setText("00:00");
            tvTotalTime.setText("00:00");
            tvRepeatInfo.setVisibility(View.GONE);
            seekBarPlayback.setProgress(0);
        }
    }
    
    /**
     * 更新时间显示
     */
    private void updateTimeDisplay(int progress, int duration) {
        // 将毫秒转换为时:分:秒格式
        String currentTimeStr = formatTime(progress);
        String totalTimeStr = formatTime(duration);
        
        tvCurrentTime.setText(currentTimeStr);
        tvTotalTime.setText(totalTimeStr);
    }
    
    /**
     * 格式化时间（毫秒转为时:分:秒）
     */
    private String formatTime(int timeMs) {
        int totalSeconds = timeMs / 1000;
        int hours = totalSeconds / 3600;
        int minutes = (totalSeconds % 3600) / 60;
        int seconds = totalSeconds % 60;
        
        if (hours > 0) {
            return getString(R.string.time_format_long, hours, minutes, seconds);
        } else {
            return getString(R.string.time_format, minutes, seconds);
        }
    }
    
    /**
     * 开始更新进度条
     */
    private void startProgressUpdates() {
        // 先停止之前的更新
        stopProgressUpdates();
        // 开始新的更新
        progressHandler.postDelayed(progressRunnable, PROGRESS_UPDATE_INTERVAL);
    }
    
    /**
     * 停止更新进度条
     */
    private void stopProgressUpdates() {
        progressHandler.removeCallbacks(progressRunnable);
    }

    @Override
    protected void onResume() {
        super.onResume();
        
        // 如果有正在播放的曲目，开始更新进度条
        if (isBound && musicService != null && musicService.isPlaying()) {
            startProgressUpdates();
            updatePlaybackProgress(); // 立即更新一次
        }
        
        // 如果服务已绑定，更新UI显示
        if (isBound && musicService != null) {
            // 仅更新UI显示，不改变播放列表
            updateUI();
        } else {
            // 如果服务未绑定，尝试绑定服务
            startMusicService();
        }
        
        // 检查是否是从播放列表管理界面返回，带有明确的action
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("action")) {
            // 只有当有明确的action指令时才处理意图
            handleIntent(intent);
            // 处理完后清除action，防止重复处理
            intent.removeExtra("action");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 停止更新进度条
        stopProgressUpdates();
    }

    /**
     * 显示曲目设置对话框，用于修改播放速度和重复次数
     * @param position 曲目在列表中的位置
     */
    private void showTrackSettingsDialog(int position) {
        AudioTrack track = currentTracks.get(position);
        if (track == null) return;

        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_track_settings, null);
        
        TextView tvTitle = view.findViewById(R.id.tvDialogTitle);
        android.widget.SeekBar seekBarSpeed = view.findViewById(R.id.seekBarSpeed);
        TextView tvSpeedValue = view.findViewById(R.id.tvSpeedValue);
        android.widget.EditText etRepeatCount = view.findViewById(R.id.etRepeatCount);
        Button btnSave = view.findViewById(R.id.btnSave);

        tvTitle.setText(track.getTitle());
        
        // 设置播放速度，范围0.5x-16.0x
        // 将播放速度映射到进度条的值（0-100）
        float minSpeed = 0.5f;
        float speed1 = track.getPlaybackSpeed();
        
        // 使用对数映射，将 0.5-16 映射到 0-100
        int speedProgress;
        if (speed1 <= 1.0f) {
            // 0-25 映射到 0.5-1.0
            speedProgress = (int)((speed1 - minSpeed) / (1.0f - minSpeed) * 25);
        } else if (speed1 <= 4.0f) {
            // 25-50 映射到 1.0-4.0
            speedProgress = (int)(25 + (speed1 - 1.0f) / (4.0f - 1.0f) * 25);
        } else {
            // 50-100 映射到 4.0-16.0
            speedProgress = (int)(50 + (speed1 - 4.0f) / (16.0f - 4.0f) * 50);
        }
        
        seekBarSpeed.setProgress(speedProgress);
        tvSpeedValue.setText(String.format("%.1fx", speed1));
        
        etRepeatCount.setText(String.valueOf(track.getRepeatCount()));

        seekBarSpeed.setOnSeekBarChangeListener(new android.widget.SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(android.widget.SeekBar seekBar, int progress, boolean fromUser) {
                float speed2;
                if (progress <= 25) {
                    // 0-25 映射到 0.5-1.0
                    speed2 = 0.5f + (progress / 25f) * 0.5f;
                } else if (progress <= 50) {
                    // 25-50 映射到 1.0-4.0
                    speed2 = 1.0f + ((progress - 25) / 25f) * 3.0f;
                } else {
                    // 50-100 映射到 4.0-16.0
                    speed2 = 4.0f + ((progress - 50) / 50f) * 12.0f;
                }
                tvSpeedValue.setText(String.format("%.1fx", speed2));
            }

            @Override
            public void onStartTrackingTouch(android.widget.SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(android.widget.SeekBar seekBar) {}
        });

        androidx.appcompat.app.AlertDialog dialog = builder.setView(view).create();

        btnSave.setOnClickListener(v -> {
            float speed;
            int progress = seekBarSpeed.getProgress();
            if (progress <= 25) {
                // 0-25 映射到 0.5-1.0
                speed = 0.5f + (progress / 25f) * 0.5f;
            } else if (progress <= 50) {
                // 25-50 映射到 1.0-4.0
                speed = 1.0f + ((progress - 25) / 25f) * 3.0f;
            } else {
                // 50-100 映射到 4.0-16.0
                speed = 4.0f + ((progress - 50) / 50f) * 12.0f;
            }
            int repeatCount;
            try {
                repeatCount = Integer.parseInt(etRepeatCount.getText().toString());
                if (repeatCount < 1) repeatCount = 1;
            } catch (NumberFormatException e) {
                repeatCount = 1;
            }

            track.setPlaybackSpeed(speed);
            track.setRepeatCount(repeatCount);
            
            // 检查是否正在播放这个曲目
            boolean isCurrentlyPlaying = false;
            if (isBound && musicService.isPlaying() && musicService.getCurrentTrackIndex() == position) {
                isCurrentlyPlaying = true;
            }
            
            // 如果当前正在播放这个曲目，更新播放速度和重复次数
            if (isCurrentlyPlaying) {
                musicService.setPlaybackSpeed(speed);
                musicService.setRepeatCount(repeatCount);
                Log.d(TAG, "已实时更新当前播放曲目的速度为: " + speed + ", 重复次数为: " + repeatCount);
            }
            
            // 保存播放列表到存储
            String currentPlaylistId = PlaylistStorage.getCurrentPlaylistId(this);
            if (currentPlaylistId != null) {
                Playlist playlist = PlaylistStorage.loadPlaylist(this, currentPlaylistId);
                if (playlist != null) {
                    playlist.setTracks(currentTracks);
                    PlaylistStorage.savePlaylist(this, playlist);
                    Log.d(TAG, "修改音频设置后保存播放列表，共 " + currentTracks.size() + " 个音频");
                }
            }
            
            // 更新UI
            trackAdapter.notifyItemChanged(position + 1); // +1 因为有header
            dialog.dismiss();
        });

        dialog.show();
    }

    @Override
    protected void onDestroy() {
        // 停止更新进度条
        stopProgressUpdates();
        
        if (isBound) {
            unbindService(serviceConnection);
            isBound = false;
        }
        super.onDestroy();
    }
}